﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Sub.TaskPlanningDesk.WebSite.ViewModels;
using Sub.TaskPlanningDesk.Model.Services.Account;
using Sub.TaskPlanningDesk.WebSite.ViewModels.Account;
using Sub.TaskPlanningDesk.WebSite.Infrastructure;

namespace Sub.TaskPlanningDesk.WebSite.Controllers
{
	public class AccountController : Controller
	{
		#region ctor

		private IFormsAuthenticationService _formsService;
		private IMembershipService _membershipService;

		public AccountController(IFormsAuthenticationService formsService,
			IMembershipService membershipService)
		{
			_formsService = formsService;
			_membershipService = membershipService;
		}

		#endregion

		public ActionResult LogOn()
		{
			return View();
		}

		[HttpPost]
		public ActionResult LogOn(LogOnModel model, string returnUrl)
		{
			if (ModelState.IsValid)
			{
				if (_membershipService.ValidateUser(model.UserName, model.Password))
				{
					_formsService.SignIn(model.UserName, model.RememberMe);
					if (Url.IsLocalUrl(returnUrl))
					{
						return Redirect(returnUrl);
					}
					else
					{
						return RedirectToAction(TheActions.Home.Index, TheControllers.Home);
					}
				}
				else
				{
					ModelState.AddModelError("", "The user name or password provided is incorrect.");
				}
			}

			// If we got this far, something failed, redisplay form
			return View(model);
		}

		public ActionResult LogOff()
		{
			_formsService.SignOut();

			return RedirectToAction(TheActions.Home.Index, TheControllers.Home);
		}
	}
}
